package com.styp152.Android.File.TakeNote;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Editor extends Activity {

	private final static String NOTES = "notes.txt";
	private EditText editor;

	@Override
	public void onCreate(final Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.editor);
		editor = (EditText) findViewById(R.id.editor);
		Button btnClose = (Button) findViewById(R.id.close);

		btnClose.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				if (showDialog(R.string.close_condition, icicle)) {
					finish();
				}
			}

		});

		Button btnSave = (Button) findViewById(R.id.close);

		btnSave.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {

				finish();
			}

		});
	}

	public void onResume() {
		super.onResume();
		try {
			InputStream in = openFileInput(NOTES);
			if (in != null) {
				InputStreamReader tmp = new InputStreamReader(in);
				BufferedReader reader = new BufferedReader(tmp);
				String str;
				StringBuffer buf = new StringBuffer();
				while ((str = reader.readLine()) != null) {
					buf.append(str + "\n");
				}
				in.close();
				editor.setText(buf.toString());
			}
		} catch (java.io.FileNotFoundException e) {
			// that's OK, we probably haven't created it yet
		} catch (Throwable t) {
			Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
		}
	}

	public void onPause() {
		super.onPause();
		try {
			OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
					NOTES, MODE_WORLD_READABLE));
			out.write(editor.getText().toString());
			out.close();
		} catch (Throwable t) {
			Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
		}
	}
}
